package com.xq.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 签名工具类
 *
 * @author xu
 * 2021/8/4 11:51
 */
public class SignGenUtil {
    /**
     * 对检索参数按键值key进行排序，拼接为参数字符串，然后进行MD5加密生成sign
     * sign标签生成方法
     * @param params 检索参数
     * @return
     */
    public static String getSign(Map<String, String> params) {
        String sign = "";
        StringBuilder paramString = new StringBuilder();
        //业务请求参数拼接
        Collection<String> keySet= params.keySet();
        List<String> list = new ArrayList<String>(keySet);
        Collections.sort(list);//对key键值按字典升序排序
        String key = "";
        for (String s : list) {
            key = s;
            if (key != null && !key.trim().equalsIgnoreCase("")) {
                if (key.equalsIgnoreCase("params")) {
                    paramString.append(params.get(key).trim());
                } else {
                    paramString.append(key.trim()).append("=").append(params.get(key).trim());
                }
                paramString.append("&");
            }
        }
        if (!paramString.toString().equals("")) {
            paramString = new StringBuilder(paramString.substring(0, paramString.length() - 1));
        }
        //进行MD5运算
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            byte[] byteArray = md5.digest(paramString.toString().getBytes(StandardCharsets.UTF_8));

            StringBuilder md5StrBuff = new StringBuilder();
            //将加密后的byte数组转换为十六进制的字符串,否则的话生成的字符串会乱码
            for (byte b : byteArray) {
                if (Integer.toHexString(0xFF & b).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & b));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & b));
                }
            }
            sign = md5StrBuff.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return sign;
    }

}
